package com.wmeimob.fastboot.jiubei.controller;

import com.github.pagehelper.PageInfo;
import com.wmeimob.fastboot.core.context.PageContext;
import com.wmeimob.fastboot.core.exception.CustomException;
import com.wmeimob.fastboot.jiubei.entity.Member;
import com.wmeimob.fastboot.jiubei.entity.ShopGoods;
import com.wmeimob.fastboot.jiubei.entity.ShopOrders;
import com.wmeimob.fastboot.jiubei.entity.UserAddress;
import com.wmeimob.fastboot.jiubei.enums.PayTypesEnum;
import com.wmeimob.fastboot.jiubei.enums.ShopOrdersStatusEnum;
import com.wmeimob.fastboot.jiubei.result.RestResponse;
import com.wmeimob.fastboot.jiubei.result.RestResults;
import com.wmeimob.fastboot.jiubei.service.MemberService;
import com.wmeimob.fastboot.jiubei.service.ShopOrdersService;
import com.wmeimob.fastboot.jiubei.service.ShopGoodsStatisticsService;
import com.wmeimob.fastboot.jiubei.service.UserAddressService;
import com.wmeimob.fastboot.starter.security.context.SecurityContext;
import com.wmeimob.fastboot.util.InputValidator;
import com.wmeimob.fastboot.wechat.starter.config.WechatPayProperties;
import lombok.extern.slf4j.Slf4j;
import me.hao0.common.xml.XmlReaders;
import me.hao0.wepay.core.Wepay;
import me.hao0.wepay.core.WepayBuilder;
import me.hao0.wepay.util.Maps;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ExecutorService;

import static java.util.concurrent.Executors.newFixedThreadPool;

/**
 * @author wjt
 * @version 1.0
 * @className ShopOrdersController
 * @description 【订单】控制器
 * @date Mon Aug 31 23:57:11 CST 2020
 **/
@RestController
@RequestMapping("shopOrders")
@Slf4j
public class ShopOrdersController {

    @Resource
    private ShopOrdersService shopOrdersService;
    @Resource
    private MemberService memberService;
    @Resource
    private WechatPayProperties wechatPayProperties;
    @Resource
    private ShopGoodsStatisticsService shopGoodsStatisticsService;
    @Resource
    private UserAddressService userAddressService;
    private static final ExecutorService EXECUTOR = newFixedThreadPool(10);

    /**
     * 订单分页查询
     *
     * @param shopOrders
     * @return
     */
    @GetMapping
    public RestResults queryForShopOrders(ShopOrders shopOrders) {
        PageContext.startPage();
        return RestResponse.makeOKRsp(new PageInfo<ShopOrders>(shopOrdersService.findListByCondition(shopOrders)));
    }


    /**
     * 订单查询-<通过id查询>
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public RestResults queryForShopOrdersById(@PathVariable("id") Long id) {
        return RestResponse.makeOKRsp(shopOrdersService.queryShopOrdersById(id));
    }


    /**
     * 订单添加
     *
     * @param shopOrders
     * @return
     */
    @PostMapping
    public RestResults insertForShopOrders(@RequestBody ShopOrders shopOrders) {
        shopOrdersService.addShopOrders(shopOrders);
        return RestResponse.makeOKRsp();
    }


    /**
     * 订单修改
     *
     * @param shopOrders
     * @return
     */
    @PutMapping
    public RestResults updateForShopOrders(@RequestBody ShopOrders shopOrders) {
        shopOrdersService.modifyShopOrders(shopOrders);
        return RestResponse.makeOKRsp();
    }

    /**
     * 订单删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public RestResults removeForShopOrders(@PathVariable("id") Long id) {
        shopOrdersService.removeShopOrders(id);
        return RestResponse.makeOKRsp();

    }

    /**
     * 发货
     */
    @PutMapping("/ship")
    public RestResults ship(@RequestBody ShopOrders shopOrders) {
        shopOrdersService.ship(shopOrders);
        return RestResponse.makeOKRsp();
    }

    /**
     * 计算订单
     */
    @PostMapping("/calculate")
    public RestResults calculateOrder(@RequestBody ShopOrders orders) {
        //判断订单类型是否为空
        //查询用户是否注册，没有注册不得购买
        Member member = SecurityContext.getUser();
        member = memberService.queryMemberById(member.getId());
        orders.setUserId(member.getId());
        ShopOrders newOrder = shopOrdersService.calculateOrders(orders);
        ShopOrders resultOrder = new ShopOrders();
        resultOrder.setOrderAmount(newOrder.getOrderAmount());
        resultOrder.setPayAmount(newOrder.getPayAmount());
        resultOrder.setShippingFee(newOrder.getShippingFee());
        resultOrder.setShippingDeduction(newOrder.getShippingDeduction());
        return RestResponse.makeOKRsp(resultOrder);
    }

    /**
     * 提交订单
     */
    @PostMapping("/submit")
    public RestResults submitOrder(@RequestBody ShopOrders orders) {
        Member member = SecurityContext.getUser();
        member = memberService.queryMemberById(member.getId());
        orders.setUserId(1L);
        //orders.setUserName(member.getNickname());
        //orders.setMobile(member.getPhone());
        UserAddress userAddress = userAddressService.queryUserAddressById(orders.getUserAddressId());
        if (ObjectUtils.isEmpty(userAddress)) {
            throw new UnsupportedOperationException("地址信息选取异常");
        }
        orders.setShippingProvince(userAddress.getProvince());
        orders.setShippingCity(userAddress.getCity());
        orders.setShippingDistrict(userAddress.getDistrict());
        orders.setShippingAddress(userAddress.getAddress());
        orders.setShippingMobile(userAddress.getMobile());
        orders.setShippingName(userAddress.getName());
        ShopOrders newOrder = shopOrdersService.calculateOrders(orders);
        ShopOrders resultOrder = shopOrdersService.confirmOrder(newOrder);

        //清空购物车
      /*  EXECUTOR.submit(() -> {
            List<Integer> goodsIdList = resultOrder.getItems().stream().map(LocalOrderItems::getGoodsId).collect(Collectors.toList());
            List<String> skuNoIds = resultOrder.getItems().stream().map(LocalOrderItems::getGoodsSkuNo).collect(Collectors.toList());
            shopCartService.orderAfterClear(resultOrder.getUserId(), goodsIdList, skuNoIds);
        });*/
        return RestResponse.makeOKRsp(resultOrder.getId());
    }


    /**
     * 微信支付
     *
     * @param orderId
     * @return :
     * @author : wjt
     */
    @PostMapping("/wechatPay/{id}")
    public RestResults wechatPayOrder(@PathVariable("id") Long orderId) {
        ShopOrders shopOrders = shopOrdersService.queryShopOrdersById(orderId);
        if (null == shopOrders) {
            throw new CustomException("订单不存在");
        }
        if (!ShopOrdersStatusEnum.TRADE.name().equals(shopOrders.getOrderStatus())) {
            throw new CustomException("订单状态异常");
        }
        shopOrders.setPayType(PayTypesEnum.WECHAT_PAY.getValue());
        Map<String, Object> pay = shopOrdersService.wechatPay(shopOrders);
        return RestResponse.makeOKRsp(pay);
    }
    /**
     * 微信支付
     *
     * @param orderId
     * @return :
     * @author : wjt
     */
    @PostMapping("/aliPay/{id}")
    public RestResults aliPayOrder(@PathVariable("id") Long orderId) {
        ShopOrders shopOrders = shopOrdersService.queryShopOrdersById(orderId);
        if (null == shopOrders) {
            throw new CustomException("订单不存在");
        }
        if (!ShopOrdersStatusEnum.TRADE.name().equals(shopOrders.getOrderStatus())) {
            throw new CustomException("订单状态异常");
        }
        shopOrders.setPayType(PayTypesEnum.ALI_PAY.getValue());
        Map<String, Object> pay = shopOrdersService.aliPay(shopOrders);
        return RestResponse.makeOKRsp(pay);
    }
    /**
     * 订单回调
     *
     * @param request
     * @return
     */
    @RequestMapping("/notify")
    public String notify(HttpServletRequest request) throws Exception {
        Map<String, Object> map = Maps.toMap(XmlReaders.create(request.getInputStream()));
        map.remove("#text");
        Wepay wepay = WepayBuilder.newBuilder("", this.wechatPayProperties.getMchKey(),
                this.wechatPayProperties.getMchNo()).build();
        Object out_trade_no = map.get("out_trade_no");
        Object transaction_id = map.get("transaction_id");
        if (wepay.notifies().verifySign(map)) {
            if (map.get("return_code").equals("SUCCESS")) {
                // 更新订单
                pay((String) out_trade_no, (String) transaction_id);

                return wepay.notifies().ok();
            }
            return wepay.notifies().notOk("未支付");
        }

        return wepay.notifies().notOk("valid sign error");
    }

    private void pay(String orderNo, String transactionId) {
        log.info("订单：[{}] 回调成功", orderNo);
        ShopOrders orders = shopOrdersService.queryShopOrdersByNo(orderNo);
        //增加商品销量
        shopOrdersService.updateForPaySuccess(orders);
        ShopOrders shopOrders = new ShopOrders();
        shopOrders.setId(orders.getId());
        shopOrders.setPayAt(new Date());
        shopOrders.setOrderStatus(ShopOrdersStatusEnum.DELIVERED.name());
        orders.setTransactionId(transactionId);
        shopOrdersService.modifyShopOrders(shopOrders);
        EXECUTOR.submit(() -> {
            shopGoodsStatisticsService.addRecord(orders);
        });
    }
    /**
     * 删除订单
     */
    @PostMapping("/delete/{orderId}")
    @Transactional(rollbackFor = Exception.class)
    public RestResults deleteOrder(@PathVariable Long orderId) {
        InputValidator.checkNull(orderId, "订单id为空");
        ShopOrders shopOrders = shopOrdersService.queryShopOrdersById(orderId);
        if (!ShopOrdersStatusEnum.CANCEL.name().equals(shopOrders.getOrderStatus()) && !ShopOrdersStatusEnum.DEAL_DONE.name().equals(shopOrders.getOrderStatus())) {
            throw new CustomException("该订单状态不能删除");
        }
        ShopOrders orders = new ShopOrders();
        orders.setId(orderId);
        orders.setDel(true);
        shopOrdersService.modifyShopOrders(orders);
        return RestResponse.makeOKRsp();
    }

    /**
     * 取消订单
     */
    @PostMapping("/cancel/{orderId}")
    public RestResults cancelOrder(@PathVariable Long orderId) {
        InputValidator.checkNull(orderId, "订单id为空");
        ShopOrders shopOrders = shopOrdersService.findShopOrdersById(orderId);
        if (!ShopOrdersStatusEnum.TRADE.name().equals(shopOrders.getOrderStatus())) {
            throw new CustomException("该订单状态不能取消");
        }
        ShopOrders orders = new ShopOrders();
        orders.setId(orderId);
        orders.setOrderStatus(ShopOrdersStatusEnum.CANCEL.name());
        shopOrdersService.modifyShopOrders(orders);
        shopOrdersService.rebackStock(shopOrders);
        return RestResponse.makeOKRsp();
    }
    /**
     * 申请退款
     */
    @PostMapping("/refund/{orderId}")
    public RestResults refundlOrder(@PathVariable Long orderId) {
        InputValidator.checkNull(orderId, "订单id为空");
        ShopOrders shopOrders = shopOrdersService.queryShopOrdersById(orderId);
        if (!ShopOrdersStatusEnum.SEND.name().equals(shopOrders.getOrderStatus())&&!ShopOrdersStatusEnum.DEAL_DONE.name().equals(shopOrders.getOrderStatus())
        &&!ShopOrdersStatusEnum.COMMENT.name().equals(shopOrders.getOrderStatus())) {
            throw new CustomException("该订单状态不能申请售后");
        }
        ShopOrders orders = new ShopOrders();
        orders.setId(orderId);
        orders.setOrderStatus(ShopOrdersStatusEnum.REFUND_APPLY.name());
        shopOrdersService.modifyShopOrders(orders);
        return RestResponse.makeOKRsp();
    }

    /**
     * 立即支付
     *
     * @param orderId
     * @return :
     * @author : wjt
     */
    @PostMapping("pay/{id}")
    public RestResults payOrder(@PathVariable("id") Long orderId) {
        ShopOrders shopOrders = shopOrdersService.queryShopOrdersById(orderId);
        if (null == shopOrders) {
            throw new CustomException("订单不存在");
        }
        if (!ShopOrdersStatusEnum.DELIVERED.name().equals(shopOrders.getOrderStatus())) {
            throw new CustomException("订单状态异常");
        }
        Map<String, Object> pay = shopOrdersService.pay(shopOrders);
        return RestResponse.makeOKRsp(pay);
    }
}
